<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:">
                        <RiskEntryInput id="fundCode" @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="资产单元编号:" v-show="SHOW_SECURITY">
                        <el-select v-model="instruction.assetCode" size="mini">
                            <el-option
                                v-for="i in computedAssetCodeSelectData"
                                :key="i.assetCode"
                                :label="i.assetCode + ' ' + i.assetName"
                                :value="i.assetCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="组合编码:">
                        <el-select
                            name="组合编码"
                            v-model="instruction.fundAccountCode"
                            @change="handleChange($event, 'fundAccountCode')"
                            size="mini"
                        >
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码">
                        <el-select
                            name="证券代码"
                            v-model="instruction.stockCode"
                            @visible-change="handleStockVisibleChange"
                            @change="handleChange($event, 'stockCode')"
                            filterable
                            remote
                            :remote-method="getstockCodeList"
                            :loading="selectLoading"
                            size="mini"
                            clearable
                            @clear="handleClearStock"
                        >
                            <el-option
                                v-for="i in stockReport"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockNameSt"
                                :value="i.stockCode"
                                :name="'stockCode' + i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select name="业务类型" v-model="instruction.businessType" size="mini" @change="handleChange($event, 'businessType')">
                            <el-option v-for="i in defaultStockBusinessTypes" :key="i.value" :label="i.value + ' ' + i.label" :value="i.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select
                            name="委托方向"
                            v-model="instruction.orderDirection"
                            size="mini"
                            :class="['font-color-' + textColor]"
                            @change="handleChange($event, 'orderDirection')"
                        >
                            <el-option
                                v-for="i in orderDirectionData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleTextColor(i.dictKey)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="期限:">
                        <!-- <RiskInputNumber
                            :input="instruction.deadline"
                            :inputAfter="'天'"
                            :maxlength="15"
                            :precision="0"
                            :field="'deadline'"
                            @getInputNumber="getInputNumber(arguments)"
                            :colorStyle="textColor"
                        >
                        </RiskInputNumber> -->
                        <el-select name="期限" v-model="instruction.deadline" size="small" @change="handleChange($event, 'deadline')">
                            <el-option
                                v-for="item in deadlineSelectData"
                                :key="item.dicKey"
                                :label="item.dicKeyName"
                                :value="item.value"
                                :name="item.dicKeyName"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="费率:" style="margin-top: 3px">
                        <RiskInputNumber
                            :input="instruction.rate"
                            :inputAfter="'%'"
                            :precision="2"
                            :maxlength="15"
                            :field="'rate'"
                            :disabled="rateDisable"
                            @getInputNumber="getInputNumber(arguments)"
                            :colorStyle="textColor"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="合约编号:" v-if="instruction.orderDirection == 'M' || (notMesh && instruction.orderDirection == '98')">
                        <el-select
                            name="originDealNo"
                            v-model="instruction.originDealNo"
                            @visible-change="handleOriginDealNoVisibleChange"
                            clearable
                            filterable
                            remote
                            :remote-method="getOriginDealNo"
                            :loading="selectLoading"
                            size="mini"
                            @clear="getOriginDealNo('')"
                        >
                            <el-option
                                v-for="i in originDealNoData"
                                :key="i.dictCode"
                                :label="i.dictCode"
                                :value="i.dictCode"
                                :name="'originDealNo' + i.dictCode"
                                @click.native="handleClickOriginDealNo(i)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="amountShowLabel">
                        <RiskInputNumber
                            :readonly="!instruction.stockCode"
                            :input="instruction.orderAmount"
                            :inputAfter="'股'"
                            :field="'orderAmount'"
                            :maxlength="15"
                            :precision="2"
                            :colorStyle="textColor"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="提前了结日期:" v-if="instruction.orderDirection == '98' && notMesh">
                        <el-date-picker
                            name="提前了结日期"
                            v-model="instruction.advanceSettleDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            style="width: 100%"
                            @change="handleChange($event, 'advanceSettleDate')"
                        ></el-date-picker
                    ></el-form-item>
                    <el-form-item label="交易对手:">
                        <el-select
                            name="交易对手"
                            id="multiAndSearch"
                            v-model="instruction.opponentCode"
                            @change="handleChange($event, 'opponentCode')"
                            clearable
                            filterable
                            remote
                            :remote-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="changeSelect"
                        >
                            <el-option
                                v-for="i in opponentReport"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                                :name="'opponentCode' + i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="目标类型:">
                        <el-select name="目标类型" v-model="instruction.targetType" size="mini" disabled>
                            <el-option v-for="(value, key) in targetTypePojo" :key="key" :label="value" :value="key"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="instruction.orderDirection == 'l'">
                        <el-checkbox
                            v-model="instruction.strategyPlacing"
                            :true-label="1"
                            :false-label="0"
                            @change="handleChange($event, 'strategyPlacing')"
                            >限售出借</el-checkbox
                        >
                    </el-form-item>
                    <!-- <RefinanceForm :stockCode="instruction.stockCode" @getForm="getForm(arguments)" :formDetail="form" /> -->
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { getConfigItem, handleLimitAmount, handleTextColor, uniqueFunc } from '@/utils/tools';
import { getSystem } from '@/utils/user-util';
import moment from 'moment';

@Component({
    name: 'RefinancingRiskOrder',
    components: {
        RiskEntryInput,
        RiskInputNumber,
    },
})

// 交易所指令
export default class RefinancingRiskOrder extends Vue {
    @Prop()
    detail: any;
    @Prop()
    stockInfoCache: any;
    @Prop()
    renderCount: number;
    @Prop()
    notMesh: boolean; // 非风险试算页面
    @Prop()
    tableSelectedRefinancingInfo: any; // 表格选中的转融通信息
    Invest: any = new Invest();
    handleTextColor = handleTextColor;
    stockReport: any[] = []; // 证券代码下拉

    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态

    stockInfo: any = {}; // 选择证券信息

    textColor: string = ''; // 文本颜色

    opponentReportState: boolean = false;

    opponentReport: any[] = []; // 发行人下拉

    deadlineSelectData: any[] = [
        {
            dicKey: '1',
            dicKeyName: '3天',
            value: '3',
        },
        {
            dicKey: '2',
            dicKeyName: '7天',
            value: '7',
        },
        {
            dicKey: '3',
            dicKeyName: '14天',
            value: '14',
        },
        {
            dicKey: '4',
            dicKeyName: '28天',
            value: '28',
        },
        {
            dicKey: '5',
            dicKeyName: '182天',
            value: '182',
        },
    ]; // 期限下拉数据

    // 基础查询条件
    private instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        orderDirection: 'l', // 委托方向
        stockCode: '',
        fundNameSt: '',
        fundAccountName: '',
        assetCode: '',
        assetName: '',
        businessType: '1', // 业务类型

        deadline: '', // 期限
        rate: '', // 费率
        orderAmount: '', // 融出数量
        opponentCode: '', // 交易对手
        lastPriceOrorderPrice: '',
        targetType: '1',
        strategyPlacing: 0,
        originDealNo: '',
        advanceSettleDate: '',
    };

    fundCodeSelectData: any[] = []; // 产品序号下拉框数据

    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据

    orderDirectionPojo: any = {
        l: '证券转融通融出',
        '98': '转融通提前了结',
        M: '融出展期',
    };
    originDealNoData: any[] = []; // 合约编号下拉框数据

    // 委托方向数据
    orderDirectionData: any[] = [
        {
            dictKey: 'l',
            dictKeyName: '证券转融通融出',
        },
        {
            dictKey: '98',
            dictKeyName: '转融通提前了结',
        },
        {
            dictKey: 'M',
            dictKeyName: '融出展期',
        },
    ];

    // 业务类型
    defaultStockBusinessTypes: SelectOptionItemData[] = [
        {
            label: '交易所业务',
            value: '1',
        },
    ];
    targetTypePojo: any = {}; // 目标类型枚举
    changeFlag: string = '2';
    // 开通上交所注册制改革(0 否 1 是 默认值0)
    isEnableSseReg: any = (getSystem().find(item => item.paramKey == 'ENABLE_SSE_REG') || {}).paramValue || '0';
    // 指令信息回显
    @Watch('renderCount', { immediate: true, deep: true })
    async setForm() {
        if (this.renderCount && this.detail && Object.keys(this.detail).length) {
            let instruction = this.detail;
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });
            if (instruction.stockCode) {
                let reportCode = instruction.stockCode.split(' ');
                instruction.reportCode = reportCode[0];
            }
            if (instruction.deadline) {
                instruction.deadline = instruction.deadline.toString();
            }
            // if (instruction.rate) {
            //     instruction.rate = instruction.rate * 100;
            // }

            instruction.targetType = '1';
            this.getOpponentCode(instruction.opponentCode || '');
            if (instruction.orderDirection == 'M' || (this.notMesh && instruction.orderDirection == '98')) {
                this.getOriginDealNo(instruction.originDealNo);
            }
            let res: any = await this.getstockCodeList(instruction.reportCode);
            if (res) {
                this.stockReport = res;
                this.stockInfo = this.stockReport.find(item => item.stockCode === instruction.stockCode);
                this.$emit('getStockInfo', this.stockInfo, '14');

                this.settingValues(instruction);

                this.selectLoading = false;
            } else {
                this.selectLoading = false;
            }
        } else {
            this.resetValues();
            this.handleClearStock();
        }
    }

    /**
     * 监听表格选中的转融通信息
     */

    @Watch('tableSelectedRefinancingInfo', { immediate: true, deep: true })
    async watchSelectedRefinancingInfo(newData, oldData) {
        if (JSON.stringify(newData) !== JSON.stringify(oldData) && this.tableSelectedRefinancingInfo) {
            // TODO 委托方向暂时默认处理成转融通提前了结
            this.instruction.orderDirection = '98';
            this.handleOrderDirectionChange(this.instruction.orderDirection);
            // this.tableSelectedRefinancingInfo.originDealNo
            this.instruction.originDealNo = this.tableSelectedRefinancingInfo.contractNo; // 合约编号
            this.instruction['contractNo'] = this.tableSelectedRefinancingInfo.contractNo; // TODO 提前了结合约编号（在途持仓序号）
            this.handleClickOriginDealNo({
                dictCode: this.tableSelectedRefinancingInfo.contractNo,
                param2: this.tableSelectedRefinancingInfo.fundCode,
                param3: this.tableSelectedRefinancingInfo.stockCode,
                param4: this.tableSelectedRefinancingInfo.marketAmount,
            });
            this.$emit('resetTableSelected');
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction.orderDirection', { immediate: true, deep: true })
    handleFieldColor() {
        if (['l'].includes(this.instruction.orderDirection)) {
            this.textColor = 'green';
        } else if (this.instruction.orderDirection == '98') {
            this.textColor = 'red';
        } else {
            // M 融出展期 颜色待定
            this.textColor = '';
        }
    }

    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 监听 资产单元计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedAssetCodeSelectData', { immediate: true, deep: true })
    watchcomputedAssetCode(newData) {
        if (!this.SHOW_SECURITY) {
            return;
        }
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.assetCode == this.instruction.assetCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.fundAccountCode == this.instruction.fundAccountCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
        this.instruction.fundAccountCode = obj.fundAccountCode;
        this.instruction.fundAccountName = obj.fundAccountName;
        this.$emit('handleSettingValue', { ...this.instruction }, '14');
    }

    get computedAssetCodeSelectData(): any {
        return uniqueFunc(this.fundAccountCodeSelectData[this.instruction.fundCode], 'assetCode');
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.instruction.fundCode];
        let retData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.instruction.assetCode);
            retData = obj || [];
        } else {
            retData = data;
        }
        return retData;
    }

    // 费率可手动编辑
    get rateDisable() {
        if (this.isEnableSseReg == '0') {
            // 未开启上交所注册制
            return true;
        }
        if (this.stockInfo && this.stockInfo.stockProperty) {
            const isSh = this.stockInfo.stockProperty == '0' && this.stockInfo.marketCode == '1';
            return !isSh;
        } else {
            return true;
        }
    }

    // 数量显示名称
    get amountShowLabel() {
        const orderDirection = this.instruction.orderDirection;
        if (orderDirection == 'l' || !this.notMesh) {
            return '融出数量:';
        } else if (orderDirection == '98') {
            return '了结数量:';
        } else if (orderDirection == 'M') {
            return '展期数量:';
        }
    }

    async mounted() {
        // 获取目标类型
        this.targetTypePojo = DictionConstUtil.targetType;
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // // 获取证券代码下拉框数据
        // this.getstockCodeList('');

        this.getOpponentCode('');

        this.changeSelect(false);
    }

    // 更改交易对手方选择框样式
    changeSelect(state: boolean) {
        let obj = document.getElementById('multiAndSearch').parentNode.querySelector('.el-select__caret');
        obj.classList.add('el-icon-arrow-up');
        if (state) {
            obj.classList.add('is-reverse');
        } else {
            obj.classList.remove('is-reverse');
        }
    }

    // // 获取子表单
    // getForm(args: any) {
    //     this.form = JSON.parse(JSON.stringify(args[0]));

    //     this.instruction.orderDirection = this.instruction.orderDirection || this.orderDirectionData[0].dictKey;

    //     this[args[1]] = args[0];

    //     this.$emit('handleSettingValue', { ...this.instruction, ...this[args[1]] }, '14');
    // }

    // 参数变动
    async handleChange(value, field) {
        if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'fundAccountCode') {
            this.handleFundAccountCodeChange(value);
        } else if (field === 'stockCode') {
            await this.handleStockCodeChange(value);
        } else if (field === 'deadline') {
            await this.getrefinancingRate(value, 1);
        } else if (field === 'orderAmount') {
            setTimeout(() => {
                this.handleOrderAmount(value);
                this.$emit('handleSettingValue', { ...this.instruction }, '14');
            }, 10);
        } else if (field === 'orderDirection') {
            this.handleOrderDirectionChange(value);
        }

        this.$emit('handleSettingValue', { ...this.instruction }, '14');
    }

    /**
     * 点击合同编号下拉数据行
     */
    async handleClickOriginDealNo(item: any) {
        console.log(item);
        this.instruction.fundCode = item.param2;
        // TODO  产品代码返回所有数据,仅有筛选功能
        this.getEntryslist(item.param2);
        this.handleChange(item.param2, 'fundCode');
        this.instruction.stockCode = item.param3;
        await this.getstockCodeList(item.param3);
        this.handleChange(item.param3, 'stockCode');
        this.instruction['marketAmount'] = item.param4;
        console.log(this.instruction, 'instruction-----------------');
    }

    handleOrderDirectionChange(value) {
        // TODO  对于"限售出借"是否需要置为''
        if (value === '98') {
            this.instruction.strategyPlacing = 0;
            !this.notMesh && (this.instruction.originDealNo = '');
            this.changeFlag = '1';
            this.instruction.advanceSettleDate = moment().format('YYYYMMDD');
            console.log(this.instruction.advanceSettleDate, 'this.instruction.advanceSettleDate');
        } else if (value == 'l') {
            this.instruction.originDealNo = '';
            this.changeFlag = '2';
        } else {
            this.instruction.strategyPlacing = 0;
            this.instruction.advanceSettleDate = '';
            this.changeFlag = '';
        }
    }

    handleOrderAmount(value) {
        if (value) {
            const marketAmount = this.instruction['marketAmount'];
            if (this.instruction.orderDirection == '98') {
                if (marketAmount < this.instruction.orderAmount) {
                    this.yh_message_warn('融出数量不可以大于原合约融出数量');
                    this.instruction.orderAmount = '';
                }
                return;
            }
            // 限定指令数量
            let limit = handleLimitAmount(this.changeFlag, this.stockInfo, value);
            if (!limit) {
                this.instruction.orderAmount = '';
            }
        }
    }

    // 设置指令中的值(回显)
    async settingValues(instruction) {
        let reportCode = '';
        if (instruction.stockCode) {
            reportCode = instruction.stockCode.split(' ');
        }
        if (!instruction.orderDirection) {
            let orderDirectionMapping = DictionConstUtil.ReversePojo(this.orderDirectionPojo);
            if (!orderDirectionMapping[instruction.orderDirectionName]) {
                return '';
            }
            instruction.orderDirection = orderDirectionMapping[instruction.orderDirectionName];
        }

        let newInstruction: any = {
            fundCode: instruction.fundCode, // 产品代码
            fundAccountCode: instruction.fundAccountCode || instruction.groupCode, // 组合编码
            reportCode: instruction.reportCode || reportCode[0], // 申报代码
            stockCode: instruction.stockCode,
            orderDirection: instruction.orderDirection, // 委托方向
            fundNameSt: instruction.fundNameSt || instruction.fundName,
            fundAccountName: instruction.fundAccountName || instruction.groupName,
            assetCode: instruction.assetCode,
            assetName: instruction.assetName,
            correspondingIndex: instruction.correspondingIndex, //
            businessType: '1',
            deadline: instruction.deadline, // 期限
            rate: instruction.rate, // 费率
            orderAmount: instruction.orderAmount, // 融出数量
            orderBalance: instruction.orderBalance,
            orderPrice: instruction.orderPrice,
            lastPriceOrorderPrice: instruction.lastPriceOrorderPrice,
            opponentCode: instruction.opponentCode, // 交易对手
            targetType: instruction.targetType,
            strategyPlacing: instruction.strategyPlacing,
            originDealNo: instruction.originDealNo,
            advanceSettleDate: instruction.advanceSettleDate,
            contractNo: instruction.contractNo,
        };
        await this.getrefinancingRate(instruction.deadline, 1);
        newInstruction.rate = this.instruction.rate;
        this.instruction = newInstruction;
    }

    // 产品代码回调
    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleChange(val, 'fundCode');
    }

    // 输入框
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        this.handleChange(value, field);
    }

    // 产品代码改变
    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
    }

    // 组合编码改变
    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.fundAccountName = fundAccount.fundAccountName;
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
    }

    // 获取证券代码下拉框数据
    getstockCodeList(val: string) {
        this.selectLoading = true;
        return new Promise((resolve, reject) => {
            this.$axios
                // .post('/original/stock/list', {
                //     multMarketCode: ['1', '2'],
                //     multStockType: [1],
                //     paging: { currentPage: 1, totalPage: 0, pageSize: 25 },
                //     stockCode: val,
                // })
                .post('/dict/stock/report/select/8', {
                    dictKey: val,
                    dictKeyName: val,
                })
                .then((res: any) => {
                    this.stockReport = res;
                    this.selectLoading = false;
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                    this.selectLoading = false;
                });
        });
    }

    handleStockVisibleChange(val) {
        if (!this.instruction.stockCode && val && !this.stockReport.length) {
            this.getstockCodeList('');
        }
    }

    handleOriginDealNoVisibleChange(val) {
        if (!this.instruction.originDealNo && val && !this.originDealNoData.length) {
            this.getOriginDealNo('');
        }
    }

    // 证券代码选择变动事件
    async handleStockCodeChange(value: string) {
        this.instruction.reportCode = '';
        if (value) {
            this.stockInfo = this.stockReport.find(item => item.stockCode === value);
            console.log(this.stockInfo, 'this.stockInfo');

            this.$emit('getStockInfo', this.stockInfo, '14');
            this.instruction.reportCode = this.stockInfo.reportCode;
            this.instruction.stockCode = this.stockInfo.stockCode;
            // this.instruction.lastPriceOrorderPrice = this.stockInfo.lastPrice;
            await this.getPrice(this.stockInfo.stockCode);

            if (this.rateDisable && this.isEnableSseReg == '1') {
                // 为上交所主板可以自由调整,则不需根据期限调用接口重置,可编辑;不为时恢复,不可编辑
                this.instruction.deadline && (await this.getrefinancingRate(this.instruction.deadline, 1));
                return;
            }
        }
    }

    /**
     * 获取券价
     */
    getPrice(stockCode: string) {
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/dataEngine/getStockPrice/' + stockCode)
                .then((result: any) => {
                    this.instruction.lastPriceOrorderPrice = result.toString();
                    resolve(result);
                })
                .catch(err => {
                    this.instruction.lastPriceOrorderPrice = '';
                    reject(err);
                });
        });
    }

    // 证券代码清除事件
    handleClearStock() {
        this.getstockCodeList('');
        this.stockInfo = null;
    }

    // 获取交易对手方信息
    private getOpponentCode(value: string) {
        this.opponentReportState = true;
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentReport = res;
                this.opponentReportState = false;
            })
            .catch(() => {
                this.opponentReportState = false;
            });
    }

    // 获取转融通费率
    async getrefinancingRate(term, type) {
        // 不选择期限时不调用接口
        if (!term) {
            return;
        }
        await this.$axios
            .post('/dict/query/refinancingRate', {
                term,
                type,
            })
            .then((res: any) => {
                this.instruction.rate = res.borrowRate * 100;
            })
            .catch(() => {});
    }

    /**
     * 重置表单数据
     */
    resetValues() {
        this.instruction.reportCode = '';
        this.instruction = {
            ...this.instruction,
            // 转融通指令额外表单数据
            deadline: '', // 期限
            rate: '', // 费率
            orderAmount: '', // 融出数量
            opponentCode: '', // 交易对手
        };
    }

    // 合约编号
    getOriginDealNo(dictKey: any) {
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/dict/securityloan/select', { dictKey: dictKey })
                .then((res: any) => {
                    this.originDealNoData = res;
                    if (res.length < 1) {
                        this.instruction.originDealNo = '';
                    }
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';

.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
    }
    .label-icon {
        border: 1.5px solid #595959;
        border-radius: 50%;
        line-height: 12px;
        font-size: 12px;
        display: inline-block;
        padding: 0 3px;
    }
    .popper {
        height: 80px;
    }
}
/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #575757 !important;
}
</style>
